package org.example.t02;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * 尝试打破双亲委派
 */
public class ParentsClassLoader  extends ClassLoader {

    /**
     * 打破双亲委派机制只能通过重写loadClass
     * @param name The <a href="#name">binary name</a> of the class
     * @return The resulting <tt>Class</tt> object
     * @throws ClassNotFoundException If the class was not found
     */
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        File f = new File("D:/IDEA/study/JVM/target/test-classes/" + name.replace(".", "/").concat(".class"));

        if(!f.exists()) return super.loadClass(name);

        try {

            InputStream is = new FileInputStream(f);

            byte[] b = new byte[is.available()];
            is.read(b);
            return defineClass(name, b, 0, b.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证最基本的
     * @throws ClassNotFoundException
     */
//    public static void main(String args[]) throws ClassNotFoundException {
//        CustomClassLoader customClassLoader = new CustomClassLoader();
//        Class<?> loadClass = customClassLoader.loadClass("org.example.AppTest");
////        customClassLoader = new CustomClassLoader();
//        Class<?> loadClassNew = customClassLoader.loadClass("org.example.AppTest");
//        System.out.println(loadClass==loadClassNew);
//        System.out.println(loadClass.getClassLoader());
//        System.out.println(loadClassNew.getClassLoader());
//    }

    /**
     * 打破双亲委派机制测试
     * @throws ClassNotFoundException
     */
    public static void main(String args[]) throws ClassNotFoundException {
        ClassLoader customClassLoader = new ParentsClassLoader();
        Class<?> loadClass = customClassLoader.loadClass("org.example.AppTest");
//        customClassLoader = new ParentsClassLoader();
        Class<?> loadClassNew = customClassLoader.loadClass("org.example.AppTest");
        System.out.println(loadClass==loadClassNew);
    }
}
